package com.jmb.api.common.utils;

import java.security.MessageDigest;

public class MD5Util {
    private static final String[] HEX_DIG_ITS={"0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"};
    public static String MD5Encode(String origin,String setName){
        // todo 检查setName是否为空还是空字符串，如果是空，这边定义了一个新的编码然后转字节数据
        String resultString;
        resultString=origin;
        try {
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            if (null == setName || "".equals(setName)){
                resultString = byteArrayToHexString(md5.digest(resultString.getBytes()));
            }else {
                resultString = byteArrayToHexString(md5.digest(resultString.getBytes(setName)));
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
        return resultString;
    }

    public static String md5ForLoginPassword(String password) {
        // 拿到用户密码盐来加密
        return MD5Encode(NoUtil.PWD_SALT + password, "utf-8");
    }

    public static String byteArrayToHexString(byte[] b) {
        StringBuilder sb = new StringBuilder();
        for (byte value : b) {
            sb.append(byteToHexString(value));
        }
        return sb.toString();
    }

    public static String byteToHexString(byte b) {
        int n = b;
        if (n < 0) {
            n += 256;
        }
        int d1 = n / 16;
        int d2 = n % 16;
        return HEX_DIG_ITS[d1] + HEX_DIG_ITS[d2];
    }

}
